package main

import (
	"fmt"
	"syncCard/logger"
	"syncCard/models"
	"syncCard/util"
)

var lg = logger.InitLog()

func main() {
	fmt.Println("开始运行")
	insRdtypes, err := util.ParseStringToMap(util.RDTYPE)
	if err != nil {
		lg.Error(err)
	}
	// fmt.Println(insRdtypes)

	connStr := fmt.Sprintf("server=%s%s;user id=%s;password=%s;database=%s;encrypt=disable;", util.Server, util.Port, util.Userid, util.Password, util.Database)

	// 获取数据
	cardDatas, err := models.GetCardData(connStr)
	if err != nil {
		lg.Error("获取数据失败 cardDatas", err)
	}

	// var wg sync.WaitGroup
	for _, cardData := range cardDatas {
		// wg.Add(1)
		// go func(cardData models.Data) {
		// defer wg.Done()
		lg.Debug("处理数据 cardData:", cardData.PerCode)
		// 处理数据 rdaccount
		rdaccount := models.RDACCOUNT{
			RDID:      cardData.PerCode,
			DEPOSIT:   util.DEPOSIT,
			PREPAY:    util.PREPAY,
			ARREARAGE: util.ARREARAGE,
			SPDEPOSIT: util.SPDEPOSIT,
		}

		timeStr := util.GetStrTimeNow()
		readerCardInfo := models.READER_CARDINFO{
			RDID:         cardData.PerCode,
			CARDID:       cardData.CardNO,
			CARDTYPE:     util.CARDTYPE,
			TRANSACTTIME: timeStr,
		}

		// 处理 reader
		var rdsex string
		if cardData.PerSex == "男" {
			rdsex = "1"
		} else {
			rdsex = "0"
		}
		// -1:预开户;0:已撤户;1:有效卡;2:挂失卡;3:冻结卡 4 预注销
		// 读者证状态，有效=1、验证=2、丢失=3、暂停=4、注销=5
		var rdcfstate string
		switch cardData.AccStatus {
		case "1":
			rdcfstate = "1"
		case "2":
			rdcfstate = "3"
		case "3":
			rdcfstate = "4"
		case "4":
			rdcfstate = "4"
		case "0":
			rdcfstate = "5"
		case "-1":
			rdcfstate = "5"
		default:
			rdcfstate = "5"
		}

		aa := insRdtypes[cardData.AccClsCode]
		if aa == "" {
			aa = insRdtypes["00"]
		}

		tdintime := util.GetStrTimeNow()

		p1 := util.Ff(cardData.PostDate)
		p2 := util.Ff(cardData.LostDate)
		reader := models.READER{
			RDID:        cardData.PerCode,
			RDPASSWD:    util.RDPASSWD,
			RDNAME:      cardData.AccName,
			RDCERTIFY:   cardData.CertCode,
			RDSEX:       rdsex,
			RDCFSTATE:   rdcfstate,
			RDTYPE:      aa,
			RDLIB:       util.RDLIB,
			RDSTARTDATE: p1,
			RDENDDATE:   p2,
			RDUNIT:      cardData.DepName,
			RDINTIME:    tdintime,
			DEPARTMANT:  "0",
			WORKCARDNO:  cardData.PerCode,
			CLASS_NUM:   cardData.DepName,
		}
		lg.Infof("reader :%v", reader)
		lg.Infof("readerCardInfo :%v", readerCardInfo)
		lg.Infof("rdaccount :%v", rdaccount)

		err = models.DataRun(util.OraServer, util.OraPort, util.OraCid, util.Orausername, util.OraPassword, &rdaccount, &readerCardInfo, &reader)
		if err != nil {
			lg.Error("DataRun Error:", err)
		}
		// }(cardData)
	}
	// wg.Wait()
}
